package com.zimmur.interceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Optional;
import com.zimmur.common.ConstData;
import com.zimmur.common.ReturnJsonEntity;
import com.zimmur.common.StatusCodeEnum;
import com.zimmur.model.dto.UserDTO;
import com.zimmur.tools.JwtTokenUtil;

public class RequestProcessingTimeInterceptor extends HandlerInterceptorAdapter {
	private Logger logger = LoggerFactory.getLogger(RequestProcessingTimeInterceptor.class);
	@Resource
	private JwtTokenUtil jwttokenUtil;
	
	@Value("#{spingMvcProperties['System.GuestId']}")
	private String guessUserId;
	
	/*public String[] allowUrls;

	public void setAllowUrls(String[] allowUrls) {
		this.allowUrls = allowUrls;
	}*/
	
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object obj, Exception ex)
			throws Exception {
		
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object obj, ModelAndView view)
			throws Exception {
	}
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
		String token=request.getParameter(ConstData.USER_ACCESS_TOKEN);
        if (token != null && !token.equals("")) {
        	Optional<UserDTO> optional = jwttokenUtil.verifyToken(request);
        	if(optional.isPresent()){
        		return true;
        	}            
        }
        ReturnJsonEntity entity = new ReturnJsonEntity();
        StatusCodeEnum statusCodeEnum = StatusCodeEnum.CODE200401;
        entity.setCode(statusCodeEnum.getCode());
        entity.setMsg(statusCodeEnum.getMsg());   
        response.setContentType("text/html;charset=UTF-8"); 
        response.getWriter().write(JSON.toJSONString(entity));
		return false;
	}
}
